import { Injectable } from '@nestjs/common';
import { FindManyOptions, Not } from 'typeorm';
import { SavePermissionDto } from './dto/permission.dto';
import { Permission } from './entities/permission.entity';
import { RedisService } from '../../../module/shared/redis/redis.service';
import { CacheEnum } from '../../../common/constants/redis.constant';

@Injectable()
export class PermissionService {
  constructor(private readonly redisService: RedisService) {}
  async save(saveDto: SavePermissionDto) {
    const exist = await Permission.existsBy({
      value: saveDto.value,
      id: saveDto?.id ? Not(saveDto.id) : undefined,
    });
    if (exist) {
      throw new Error('permission.exist');
    }
    if (saveDto?.id) {
      await this.redisService.deleteKeysByPrefix(CacheEnum.ROLE);
    }
    return await Permission.save(Permission.create(saveDto));
  }

  async findAndCount(options: FindManyOptions<Permission>) {
    const [rows, total] = await Permission.findAndCount(options);
    return { rows, total };
  }

  async delete(ids: string[]) {
    const result = await Permission.delete(ids);
    if (result.affected) {
      await this.redisService.deleteKeysByPrefix(CacheEnum.ROLE);
    }
    return result;
  }
}
